package com.chenailin.www.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author evi
 */
public class SessionUtil {
    private static final String CAPTCHA_KEY = "captcha_";
    private static final String EMAIL_CODE_KEY = "email_code_";
    // 验证码有效期5分钟
    private static final int EMAIL_CODE_EXPIRE_MINUTES = 5;

    // 图形验证码相关
    public static void setCaptcha(HttpServletRequest request, String token, String code) {
        HttpSession session = request.getSession();
        session.setAttribute(CAPTCHA_KEY + token, code);
        // 设置5分钟后过期
        session.setAttribute(CAPTCHA_KEY + token + "_expire",
                System.currentTimeMillis() + EMAIL_CODE_EXPIRE_MINUTES * 60 * 1000);
    }

    public static String getCaptcha(HttpServletRequest request, String token) {
        HttpSession session = request.getSession();
        Long expireTime = (Long) session.getAttribute(CAPTCHA_KEY + token + "_expire");
        if (expireTime != null && System.currentTimeMillis() > expireTime) {
            removeCaptcha(request, token);
            return null;
        }
        return (String) session.getAttribute(CAPTCHA_KEY + token);
    }

    public static void removeCaptcha(HttpServletRequest request, String token) {
        HttpSession session = request.getSession();
        session.removeAttribute(CAPTCHA_KEY + token);
        session.removeAttribute(CAPTCHA_KEY + token + "_expire");
    }

    // 邮箱验证码相关
    public static void setEmailCode(HttpServletRequest request, String email, String code) {
        HttpSession session = request.getSession();
        session.setAttribute(EMAIL_CODE_KEY + email, code);
        // 设置5分钟后过期
        session.setAttribute(EMAIL_CODE_KEY + email + "_expire",
                System.currentTimeMillis() + EMAIL_CODE_EXPIRE_MINUTES * 60 * 1000);
    }

    public static String getEmailCode(HttpServletRequest request, String email) {
        HttpSession session = request.getSession();
        Long expireTime = (Long) session.getAttribute(EMAIL_CODE_KEY + email + "_expire");
        if (expireTime != null && System.currentTimeMillis() > expireTime) {
            removeEmailCode(request, email);
            return null;
        }
        return (String) session.getAttribute(EMAIL_CODE_KEY + email);
    }

    public static void removeEmailCode(HttpServletRequest request, String email) {
        HttpSession session = request.getSession();
        session.removeAttribute(EMAIL_CODE_KEY + email);
        session.removeAttribute(EMAIL_CODE_KEY + email + "_expire");
    }
}